<template>
    <div>
        <el-form label-position="top" ref="addFormRef" style="margin-bottom: 10px" :model="addForm" :rules="productRules" label-width="80px">
            <div style="display:flex">
                <el-form-item label="">
                    <el-radio v-if="addFrequency =='1'||type !='edit'" v-model="addFrequency" label="1" @change="addFrequencyFn">单次套餐</el-radio>
                    <el-radio v-if="addFrequency =='2'||type !='edit'" v-model="addFrequency" label="2" @change="addFrequencyFn">多次套餐</el-radio>

                    <el-select :disabled="type =='edit'" v-if="addFrequency!=1" style="width:200px" v-model="addForm.quantity" placeholder="请选择配送次数" @change="selectMaxTime(addForm.quantity,0)">
                        <el-option v-for="item in 24" :key="item" :label="item+1" :value="item+1" />
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item label="" v-if="addFrequency!=1">
                <el-pagination background layout="pager" :total="Number(addForm.quantity) * 10" @current-change="addFormQuantityClick" style="justify-content: left;margin-top:5px" />
            </el-form-item>
            <el-form-item style="position: relative" label="套餐商品">
                <span class="el-icon-plus add-add-click" style="position: absolute; left: -25px; top: 25px; color: #409EFF;" @click="addDataItem" />
                <el-table v-for="(item, index) in addForm.itemList" v-show="addFormCurrentIndex == index" :key="index" ref="addTableFormRef" :class="'add-form-css' + index" :data="item" stripe border style="width:800px">
                    <el-table-column label="商品">
                        <template slot-scope="scope">
                            <el-form-item style="margin-bottom: 0;">
                                <el-select v-model="item[scope.$index].productId" style="width: 100%;" placeholder="请选择对应商品名称" filterable :filter-method="queryProduct" @change="addFromAddItemList(scope.$index, scope.row.productId)">
                                    <el-option v-for="item in productIdOptions" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="缩略图" width="82">
                        <template slot-scope="scope">
                            <img :key="Math.random()" style="width: 60px; height: 60px; vertical-align:middle; overflow: hidden;background-color: #F2F6FC;" :src="scope.row.productThumbnail" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column label="价格" width="110" prop="productPrice" />
                    <el-table-column label="单位" width="80" prop="unit" />
                    <el-table-column label="数量" width="110" prop="convRate">
                        <template slot-scope="scope">
                            <el-form-item>
                                <el-input v-model="scope.row.convRate" type="number" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                <a v-show="addForm.itemList[addFormCurrentIndex].length > 1" @click="addFromDelItemList(scope.$index)">
                                    <i style="color: #F56C6C" class="el-icon-delete" />
                                </a>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item style="margin-top:10px">
                <template>
                    <i class="el-icon-info" style="font-size:18px;color:#333333"></i>
                    <span style="font-size:16px;color:#333333">套餐包含 {{totalLingth.toFixed(0)}} 个商品，原价合计{{totalAmount.toFixed(2)}}元 </span>
                    <span style="font-size:16px;color:#C0C4CC">（该原价和套餐最终价格的差价不计入营销成本）</span>
                </template>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { list as productList, updateProduct } from "@/api/product";
import utils from "../../../utils/utils.js";
export default {
    data() {
        return {
            addForm: {
                quantity: "",
                productId: "",
                itemList: [],
                type: 1,
            },
            productRules: {
                quantity: [
                    {
                        required: true,
                        message: "请输入配送次数",
                        trigger: "blur",
                    },
                ],
                productId: [
                    {
                        required: true,
                        message: "请选择商品名称",
                        trigger: "blur",
                    },
                ],
                productName: [
                    {
                        required: true,
                        message: "请选择商品名称",
                        trigger: "blur",
                    },
                ],
                productPrice: [
                    {
                        required: true,
                        message: "请输入商品价格",
                        trigger: "blur",
                    },
                ],
                convRate: [
                    {
                        required: true,
                        message: "请输入捆绑系数",
                        trigger: "blur",
                    },
                ],
            },
            addFrequency: "1",
            addFormCurrentIndex: 0,
            productIdOptions: [],
            times: [],
            productParams: {
                name: "",
                type: 0,
                isList: true,
            },
            totalAmount: 0,
            totalLingth: 0,
        };
    },
    props:['type'],
    methods: {
        addFrequencyFn(e) {
            if (e == 1) {
                this.addForm.quantity = "1";
                this.addForm.itemList.length = 1;
                this.addFormCurrentIndex = 0;
                this.productParams.type = "";
            } else {
                this.addForm.quantity = "2";
                this.addForm.itemList[1] = [
                    {
                        convRate: 1,
                        groupId: 1,
                    },
                ];
                this.productParams.type = 0;
            }
            this.queryProduct();
            this.setAddClickHeight(0);
        },
        queryProduct(query) {
            clearTimeout(this.productMark);
            this.productMark = setTimeout(() => {
                this.productIdOptions = [];
                this.productParams.name = query;
//                this.productParams.type = 0
                productList(this.productParams)
                    .then((res) => {
                        this.productIdOptions = res.data.data;
                        if (utils.isNull(this.addForm.itemList)) {
                            return;
                        }
                        this.addForm.itemList.forEach((list) => {
                            // 让每一项与列表比对,找不到则添加进去
                            list.forEach((item) => {
                                const notFound = this.productIdOptions.find(
                                    (val) => {
                                        return val.id == item.productId;
                                    }
                                ); // 找到列表里没有的数据
                                if (!notFound && item.productId !== "") {
                                    const obj = {
                                        name: item.productName,
                                        id: item.productId,
                                        thumbnail: item.productThumbnail,
                                        price: item.productPrice,
                                        unit: item.unit,
                                    };
                                    this.productIdOptions.unshift(obj); // 把没有的数据添加到列表里
                                }
                            });
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }, 300);
        },
        addDataItem() {
            const obj = {
                productId: "",
                productName: "",
                productPrice: "",
                convRate: 1,
                groupId: 1,
            };
            this.addForm.itemList[this.addFormCurrentIndex].push(obj);
            this.setAddClickHeight(0);
        },
        addFormQuantityClick(index) {
            this.addFormCurrentIndex = index - 1;
            this.setAddClickHeight(0);
        },
        addShowDialog(data) {
            if (data) {
                this.addForm = data;
                const tempItemList = [];
                for (let i = 0; i < this.addForm.quantity; i++) {
                    tempItemList[i] = [];
                    for (let j = 0; j < this.addForm.itemList.length; j++) {
                        if (
                            Number(this.addForm.itemList[j].groupId) ===
                            i + 1
                        ) {
                            tempItemList[i].push(this.addForm.itemList[j]);
                        }
                    }
                }
                this.addForm.itemList = tempItemList;
                if (this.addForm.quantity > 1) {
                    this.addFrequency = "2";
                } else {
                    this.addFrequency = "1";
                }
                if (this.addForm.itemList.length == 1) {
                    this.productParams.type = "";
                } else {
                    this.productParams.type = 0;
                }
                this.queryProduct();
                this.setAddClickHeight(0);
                this.totalAmountClick()
            } else {
                console.log("套餐data");
                this.addFrequency = "1";
                this.addForm = {
                    id:'',
                    productId: "",
                    type: 1,
                    quantity: "1",
                    itemList: [
                        [
                            {
                                productName: "",
                                convRate: 1,
                                groupId: 1,
                            },
                        ],
                    ],
                };
                if (this.addForm.itemList.length == 1) {
                    this.productParams.type = "";
                } else {
                    this.productParams.type = 0;
                }
                this.queryProduct();
                this.setAddClickHeight(0);
            }
        },
        addFromAddItemList(index, productId) {
            // 给对应itemList赋值对应属性
            const OptionsIndex = this.productIdOptions.find((val) => {
                return val.id == productId;
            });
            this.addForm.itemList[this.addFormCurrentIndex][index].productName =
                OptionsIndex.name;
            this.addForm.itemList[this.addFormCurrentIndex][
                index
            ].productPrice = OptionsIndex.price;
            this.addForm.itemList[this.addFormCurrentIndex][
                index
            ].productThumbnail = OptionsIndex.thumbnail;
            this.addForm.itemList[this.addFormCurrentIndex][index].unit =
                OptionsIndex.unit;
            this.totalAmountClick()
        },
        totalAmountClick(){
            var _this = this
            _this.totalAmount = 0;
            _this.totalLingth = 0;
            // 拿到所有itemList
            for (let i = 0; i < _this.addForm.itemList.length; i++) {
                for (let j = 0; j < _this.addForm.itemList[i].length; j++) {
                    _this.totalAmount +=
                        Number(_this.addForm.itemList[i][j].productPrice) *
                        Number(_this.addForm.itemList[i][j].convRate);
                    _this.totalLingth += Number(
                        _this.addForm.itemList[i][j].convRate
                    );
                }
            }
            console.log(_this.totalAmount)
            console.log(_this.totalLingth)
            console.log('2323323')
        },
        addFromDelItemList(index) {
            // 删除itemList单项
            this.addForm.itemList[this.addFormCurrentIndex].splice(index, 1);
            this.setAddClickHeight(0);
        },
        selectMaxTime(data, type) {
            console.log(data + "----------" + type);
            this.times = [];
            if (type === 0) {
                if (data > 24) {
                    data = 24;
                    this.addForm.quantity = 24;
                }
                for (let i = 0; i < data; i++) {
                    this.addForm.itemList.push([
                        {
                            convRate: 1,
                            groupId: 1,
                        },
                    ]);
                }
                if (this.addFormCurrentIndex > this.addForm.quantity - 1) {
                    this.addFormCurrentIndex = this.addForm.quantity - 1;
                }
                this.addForm.itemList.length = this.addForm.quantity;
            }
            if (data !== null || data !== "" || data > 0) {
                for (var i = 1; i <= data; i++) {
                    this.times.push(i);
                }
            } else {
                this.times.push(0);
            }
        },
        setAddClickHeight(data) {
            let itemList;
            let mask;
            let click;
            if (data == 0) {
                // 判断要获取哪个列表的数据
                itemList = this.addForm.itemList[this.addFormCurrentIndex];
                mask = `.add-form-css${this.addFormCurrentIndex}`;
                click = ".add-add-click";
            } else {
                itemList = this.editForm.itemList[this.editFormCurrentIndex];
                mask = `.edit-form-css${this.editFormCurrentIndex}`;
                click = ".edit-add-click";
            }
            setTimeout(() => {
                // 获取表头的高度
                const tableTopHeight = document.querySelector(
                    `${mask} .el-table__header`
                ).offsetHeight;
                const tableItem = document.querySelector(`${mask}`);
                let itemClass; // 判断列表是否有数据
                if (
                    tableItem.className.indexOf(
                        "el-table--enable-row-transition"
                    ) > -1
                ) {
                    itemClass = ".el-table__row"; // 有数据
                } else {
                    itemClass = ".el-table__empty-text"; // 没数据
                }
                // 获取一行表格高度
                const tableHeight = document.querySelector(
                    `${mask} ${itemClass}`
                ).offsetHeight;
                // 获取添加按钮样式
                const addClickStyle = document.querySelector(`${click}`);
                // 获取添加按钮高度
                const addClickHeight = addClickStyle.offsetHeight;
                // 设置添加按钮的位置
                const moveHeight =
                    tableTopHeight +
                    (itemList.length > 0 ? itemList.length - 1 : 0) *
                        tableHeight +
                    (tableHeight - addClickHeight) / 2;
                /* console.log(tableTopHeight, 'tableTopHeight')
          console.log(tableHeight, 'tableHeight')
          console.log(moveHeight, 'moveHeight') */
                addClickStyle.style.top = moveHeight + "px";
            }, 100);
        },
        addClick() {
            // 新增
            this.$refs["addFormRef"].validate((valid) => {
                if (valid) {
                    const params = {
                        productId: this.addForm.productId,
                        type: 1,
                        quantity: this.addForm.quantity,
                        id:this.addForm.id,
                    };
                    const itemList = [];
                    // 拿到所有itemList
                    for (let i = 0; i < this.addForm.itemList.length; i++) {
                        for (
                            let j = 0;
                            j < this.addForm.itemList[i].length;
                            j++
                        ) {
                            if (
                                utils.isNull(
                                    this.addForm.itemList[i][j].productName
                                )
                            ) {
                                this.$message({
                                    message: "请填写商品名称",
                                    type: "warning",
                                });
                                this.$emit("mealSave", "1");
                                return;
                            } else if (
                                utils.isNull(
                                    this.addForm.itemList[i][j].convRate
                                )
                            ) {
                                this.$message({
                                    message: "请填写数量",
                                    type: "warning",
                                });
                                this.$emit("mealSave", "1");
                                return;
                            }
                            this.addForm.itemList[i][j].groupId = i + 1;
                            itemList.push(this.addForm.itemList[i][j]);
                        }
                    }
                    itemList.forEach((item, index) => {
                        // 暂时去掉单位
                        delete itemList[index].unit;
                        delete itemList[index].sn;
                    });
                    params.itemList = itemList;
                    console.log(params, "params");
                    this.$emit("mealSave", params);
                } else {
                    this.$emit("mealSave", "1");
                    return false;
                }
                this.$emit("mealSave", "1");
            });
        },
    },
};
</script>
<style scoped>
/deep/ .el-form-item {
    margin-bottom: 0px;
}
/deep/ .el-form-item__label {
    padding: 0px !important;
}
</style>
